package com.yy.yjbo.yjbonetbroadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import de.greenrobot.event.EventBus;

/**
 * 有无网络的提醒
 * 我们只在一个界面中监听是否有网；因为每个界面都提示也会影响用户的使用的；
 *
 * @author yjbo
 * @time 2017/2/10 11:17
 * @mail 1457521527@qq.com
 */
public class OtherMainActivity extends AppCompatActivity {

    TextView text_net;
    NetStateRec connectionReceiver = null;
    boolean isNet = false;

    /**
     * 监听是否有网的广播
     * @author yjbo  @time 2017/2/10 14:18
     */
    class NetStateRec extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            chooseMode();
        }
    }

    //是否有网时进行判断
    private void chooseMode() {
        if (!NetworkUtil.isConnected()) {
            text_net.setVisibility(View.VISIBLE);
        } else {
            text_net.setVisibility(View.GONE);
            if (isNet == false) {
                //之前没有网络，现在有网络了，则请求网络数据
                Toast.makeText(OtherMainActivity.this, "请求数据啦" + isNet, Toast.LENGTH_SHORT).show();
            }
        }
        isNet = NetworkUtil.isConnected();
        System.out.println("===NetStateReceiver===当前网络状态==OtherMainActivity==" + isNet);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other_main);

        text_net = (TextView) findViewById(R.id.text_net);

        isNet = NetworkUtil.isConnected();

        connectionReceiver = new NetStateRec();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(connectionReceiver, intentFilter);

        text_net.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = null;
                //判断手机系统的版本  即API大于10 就是3.0或以上版本
                if (android.os.Build.VERSION.SDK_INT > 10) {
                    intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
                } else {
                    intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                }
                startActivity(intent);
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (connectionReceiver != null) {
            unregisterReceiver(connectionReceiver);
        }
    }
}
